<template>
  <div class="app-container">
    <el-form :model="searchForm" label-width="80px" @submit.native.prevent="search()">
      <el-row>
        <!--<el-col v-if="roleType===0" class="other">-->
          <!--<el-form-item label="所属团队" size="small">-->
            <!--<el-input v-model="searchForm.teamName"></el-input>-->
          <!--</el-form-item>-->
        <!--</el-col>-->
        <el-col class="other">
          <el-form-item label="姓名" size="small">
            <el-input v-model="searchForm.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="searchBtn">
          <el-form-item size="small">
            <el-button type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!--<div class="table-btn">-->
    <!--<el-button type="primary" size="small" icon="el-icon-plus" @click="addTeam()">添加</el-button>-->
    <!--<el-button size="small" icon="el-icon-upload2">导出</el-button>-->
    <!--</div>-->
    <my-table
      :data="tableData"
      :col-configs="colConfigs"
      v-loading="listLoading"
      :page-num="pageNum"
      :page-size="pageSize"
    >
      <el-table-column
        slot="opt"
        fixed="right"
        label="操作"
        width="120">
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="editTeam(scope.row.transferId)"
            type="text"
            size="small">
            修改
          </el-button>
          <el-popover
            placement="top"
            width="160"
            :ref="`popover-${scope.$index}`"
          >
            <p>确定删除这条数据吗?</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[`popover-${scope.$index}`].doClose()">取消</el-button>
              <el-button type="primary" size="mini" @click.native.prevent="deleteRow(scope)">确定</el-button>
            </div>
            <el-button type="text" size="small" slot="reference" v-popover:popover-${scope.$index}>删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </my-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <el-dialog :title="dialogTitle" :visible.sync="outerVisible" width="440px">
      <el-form ref="teamRow" :rules="rules" :model="teamRow" label-width="110px">
        <el-form-item prop="changed" label="异动" size="small">
          <el-select v-model="teamRow.changed" placeholder="请选择">
            <el-option
              v-for="item in global.changeList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类" size="small" class="item-inline">
          <el-select v-model="teamRow.classification" placeholder="请选择">
            <el-option
              v-for="item in global.classificationList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型" size="small" class="item-inline">
          <el-select v-model="teamRow.genre" placeholder="请选择">
            <el-option
              v-for="item in global.genreList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日期" size="small">
          <el-date-picker
            v-model="teamRow.recordTime"
            type="date"
            value-format="timestamp"
            placeholder="选择日期"
            style="width: 190px">
          </el-date-picker>
        </el-form-item>
        <div v-if="teamRow.changed===1">
          <el-form-item prop="name" label="姓名" size="small">
            <el-input type="text" v-model="teamRow.name"></el-input>
          </el-form-item>
          <el-form-item label="一级部门" size="small" class="item-inline">
            <el-select v-model="teamRow.primarySector" placeholder="请选择" :disabled="teamRow.classification!==1">
              <el-option
                v-for="item in global.primarySectorList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="二级部门" size="small" class="item-inline">
            <el-select v-model="teamRow.secondarySector" placeholder="请选择" :disabled="teamRow.classification!==1"
                       @change="secondarySectorChange">
              <el-option
                v-for="item in global.secondarySectorList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="tertiarySector" label="三级部门" size="small" class="item-inline">
            <el-autocomplete
              v-model="teamRow.tertiarySector"
              :fetch-suggestions="querySearchTertiarySector"
              placeholder="请输入内容"
            >
            </el-autocomplete>
          </el-form-item>
          <el-form-item prop="teamName" label="所属团队" size="small" class="item-inline">
            <el-autocomplete
              v-model="teamRow.teamName"
              :fetch-suggestions="querySearchTeam"
              @select="handleSelectTeam"
              placeholder="请输入内容"
            >
            </el-autocomplete>
          </el-form-item>
          <el-form-item label="职务" size="small">
            <el-input type="text" v-model="teamRow.originalPosition"></el-input>
          </el-form-item>
          <el-form-item label="职级" size="small">
            <el-select v-model="teamRow.rank" placeholder="请选择">
              <el-option
                v-for="item in global.rankList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="性别" size="small">
            <el-radio-group v-model="teamRow.sex">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="0">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        <div v-else>
          <el-form-item prop="name" label="姓名" size="small">
            <el-autocomplete
              v-model="teamRow.name"
              :fetch-suggestions="querySearchName"
              @select="handleSelectName"
              placeholder="请输入内容"
            >
            </el-autocomplete>
          </el-form-item>
          <el-form-item label="一级部门" size="small" class="item-inline">
            <el-select v-model="teamRow.primarySector" disabled placeholder="请选择">
              <el-option
                v-for="item in global.primarySectorList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="二级部门" size="small" class="item-inline">
            <el-select v-model="teamRow.secondarySector" disabled placeholder="请选择">
              <el-option
                v-for="item in global.secondarySectorList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="tertiarySector" label="三级部门" size="small">
            {{teamRow.tertiarySector}}
          </el-form-item>
          <el-form-item prop="teamName" label="所属团队" size="small">
            {{teamRow.teamName}}
          </el-form-item>
          <el-form-item label="职务" size="small">
            {{teamRow.originalPosition}}
          </el-form-item>
          <el-form-item label="职级" size="small">
            {{teamRow.rank | filterRank}}
          </el-form-item>
          <el-form-item label="性别" size="small">
            {{teamRow.sex | filterSex}}
          </el-form-item>
        </div>
        <el-form-item v-if="teamRow.changed===4" label="现部门" size="small"
                      class="item-inline">
          <el-autocomplete
            v-model="teamRow.inTeamName"
            :fetch-suggestions="querySearchInTeam"
            @select="handleSelectInTeam"
            placeholder="请输入内容"
          >
          </el-autocomplete>
        </el-form-item>
        <el-form-item v-if="teamRow.changed===3 || teamRow.changed===4" label="现职务" size="small">
          <el-input type="text" v-model="teamRow.nowPosition"></el-input>
        </el-form-item>
        <el-form-item v-if="teamRow.changed===3 || teamRow.changed===4" label="现职级" size="small">
          <el-select v-model="teamRow.nowRank" placeholder="请选择">
            <el-option
              v-for="item in global.rankList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注说明" size="small">
          <el-input type="textarea" v-model="teamRow.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="warning" size="small"  @click="submitForm('teamRow')" v-no-more-click>确定</el-button>
        <el-button size="small" @click="outerVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    addPersonnelTransfer,
    deletePersonnelTransfer,
    getPersonnelTransfer,
    selectPersonnelTransfer,
    updatePersonnelTransfer,
    selectTeam,
    selectOperator
  } from '@/api/personneltransfer'
  import myTable from '@/components/myTable'
  import global from '@/components/global'

  import { AreaSelect } from 'vue-area-linkage'
  import { pca } from 'area-data'
  import { formatDate } from '@/utils/index'

  const recordTime = {
    props: ['colConfig'],
    filters: {
      formatDate(time) {
        var date = new Date(time)
        return formatDate(date, 'yyyy-MM-dd')
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        {{ scope.row[colConfig.prop] | formatDate }}
      </span>
  </el-table-column>
  `
  }

  const sex = function(row, column) {
    return row.sex ? '男' : '女'
  }

  const formatter = function(row, column) {
    if (row[column.property]) {
      let obj = {}
      obj = global[`${column.property}List`].find((item) => {
        return item.value === row[column.property] // 筛选出匹配数据
      })
      return obj.label
    }
  }

  const changed = function(row, column) {
    if (row.changed) {
      let obj = {}
      obj = global.changeList.find((item) => {
        return item.value === row.changed // 筛选出匹配数据
      })
      return obj.label
    }
  }

  export default {
    components: {
      myTable,
      AreaSelect
    },
    filters: {
      filterSex(sex) {
        return sex ? '男' : '女'
      },
      filterRank(rank) {
        if (rank) {
          let obj = {}
          obj = global.rankList.find((item) => {
            return item.value === rank // 筛选出匹配数据
          })
          return obj.label
        }
      }
    },
    data() {
      return {
        colConfigs: [
          { prop: 'changed', label: '异动', width: '100', formatter: changed },
          { prop: 'recordTime', label: '日期', width: '150', component: recordTime },
          { prop: 'classification', label: '分类', width: '100', formatter: formatter },
          { prop: 'genre', label: '类型', width: '100', formatter: formatter },
          { prop: 'primarySector', label: '一级部门', width: '100', formatter: formatter },
          { prop: 'secondarySector', label: '二级部门', width: '100', formatter: formatter },
          { prop: 'tertiarySector', label: '三级部门', width: '150' },
          { prop: 'teamName', label: '所属团队', width: '150' },
          { prop: 'name', label: '姓名', width: '150' },
          { prop: 'originalPosition', label: '职务', width: '150' },
          { prop: 'rank', label: '职级', width: '150', formatter: formatter },
          { prop: 'sex', label: '性别', width: '150', formatter: sex },
          { prop: 'inTeamName', label: '现部门', width: '150' },
          { prop: 'nowPosition', label: '现职务', width: '150' },
          { prop: 'nowRank', label: '现职级', width: '150', formatter: formatter }
          // { slot: 'opt' }
        ],
        searchForm: {},
        searchFormList: {},
        tenderNames: [],
        infoTitles: [],
        listLoading: true,
        dialogTitle: '',
        dialogType: 0,
        teamRow: {
          changed: 1
        },
        teamRowClear: {
          changed: 1
        },
        tableData: [],
        pageNum: 1,
        pageSize: 10,
        total: 1,
        outerVisible: false,
        innerVisible: false,
        pca: pca,
        rules: {
          changed: [
            { required: true, message: '请选择异动', trigger: 'change' }
          ],
          name: [
            { required: true, message: '请输入姓名', trigger: 'change' }
          ],
          sex: [
            { required: true, message: '请选择性别', trigger: 'change' }
          ],
          teamName: [
            { required: true, message: '请输入所属团队', trigger: 'change' }
          ],
          originalPosition: [
            { required: true, message: '请输入职务', trigger: 'change' }
          ],
          rank: [
            { required: true, message: '请输入职级', trigger: 'change' }
          ]
        },
        visible: false
      }
    },
    created() {
      this.teamRowClear = JSON.parse(JSON.stringify(this.teamRow))
      this.fetchData()
    },
    computed: {
      global() {
        return global
      },
      teamId() {
        return this.$store.state.user.teamId
      },
      roleType() {
        return this.$store.state.user.roleType
      },
      teamIds() {
        return this.$store.state.user.teamIds
      }
    },
    methods: {
      fetchData() {
        this.searchFormList.pageNum = this.pageNum
        this.searchFormList.pageSize = this.pageSize
        this.searchFormList.roleType = this.roleType
        this.searchFormList.teamId = this.teamId
        this.searchFormList.teamIds = this.teamIds
        this.listLoading = true
        getPersonnelTransfer(this.searchFormList).then(response => {
          this.tableData = response.responseBody.list
          this.total = response.responseBody.total
          this.listLoading = false
        })
      },
      search() {
        this.pageNum = 1
        this.searchFormList = JSON.parse(JSON.stringify(this.searchForm))
        this.fetchData()
      },
      addTeam() {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.dialogTitle = '新增人事调动'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.teamRow.isTender = 1
        this.dialogType = 1
      },
      editTeam(transferId) {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.dialogTitle = '修改人事调动'
        this.dialogType = 0
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        const params = {
          transferId: transferId
        }
        selectPersonnelTransfer(params).then(response => {
          const data = response.responseBody
          this.teamRow = Object.assign({}, this.teamRow, data)
        })
      },
      submitForm(formName) {
        const params = {
          changed: this.teamRow.changed,
          classification: this.teamRow.classification,
          genre: this.teamRow.genre,
          recordTime: this.teamRow.recordTime,
          primarySector: this.teamRow.primarySector || '',
          secondarySector: this.teamRow.secondarySector || '',
          secondarySectorName: this.teamRow.secondarySectorName || '',
          tertiarySector: this.teamRow.tertiarySector,
          teamId: this.teamRow.teamId,
          teamName: this.teamRow.teamName,
          employeeId: this.teamRow.employeeId,
          name: this.teamRow.name,
          originalPosition: this.teamRow.originalPosition,
          rank: this.teamRow.rank,
          sex: this.teamRow.sex,
          inTeamName: this.teamRow.inTeamName,
          nowPosition: this.teamRow.nowPosition,
          nowRank: this.teamRow.nowRank,
          remark: this.teamRow.remark || ''
        }
        if (this.teamRow.changed === 1) {
          params.employeeId = ''
        }
        if (this.teamRow.changed !== 4) {
          params.inTeamName = ''
        }
        if (this.teamRow.changed === 3 || this.teamRow.changed === 4) {
          params.nowPosition = this.teamRow.nowPosition || ''
          params.nowRank = this.teamRow.nowRank || ''
        } else {
          params.nowPosition = ''
          params.nowRank = ''
        }
        if (this.teamRow.classification !== 1) {
          params.primarySector = ''
          params.secondarySector = ''
          params.secondarySectorName = ''
        }
        if (!this.dialogType) {
          params.transferId = this.teamRow.transferId
        }
        if (this.teamRow.teamId) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              if (this.dialogType) {
                addPersonnelTransfer(params).then(response => {
                  console.log(response)
                  this.outerVisible = false
                  this.fetchData()
                })
              } else {
                updatePersonnelTransfer(params).then(response => {
                  console.log(response)
                  this.outerVisible = false
                  this.fetchData()
                })
              }
            } else {
              console.log('error submit!!')
              return false
            }
          })
        } else {
          this.$message({
            message: '该所属团队不存在',
            type: 'warning'
          })
        }
      },
      deleteRow(scope) {
        this.$refs[`popover-${scope.$index}`].doClose()
        const params = new FormData()
        params.append('transferId', scope.row.transferId)
        params.append('changed', scope.row.changed)
        params.append('employeeId', scope.row.employeeId)
        params.append('isDel', 1)
        deletePersonnelTransfer(params).then(response => {
          this.fetchData()
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.fetchData()
      },
      secondarySectorChange(value) {
        console.log(value)
        let obj = {}
        obj = global.secondarySectorList.find((item) => {
          return item.value === value
        })
        this.$set(this.teamRow, 'secondarySectorName', obj.label)
        console.log(this.teamRow.secondarySectorName)
      },
      querySearchTertiarySector(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        if (queryString) {
          const params = {
            teamName: queryString
          }
          selectTeam(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.teamName
            }
            let nameList = response.responseBody
            if (nameList.length === 0) {
              nameList = [{ value: '暂无数据' }]
            }
            callback(nameList)
          })
        } else {
          callback([])
        }
      },
      querySearchTeam(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.teamRow.teamId
        if (queryString) {
          const params = {
            teamName: queryString
          }
          selectTeam(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.teamName
            }
            let nameList = response.responseBody
            if (nameList.length === 0) {
              nameList = [{ value: '暂无数据' }]
            }
            callback(nameList)
          })
        } else {
          callback([])
        }
      },
      handleSelectTeam(item) {
        this.$set(this.teamRow, 'teamId', item.teamId)
        this.$set(this.teamRow, 'teamName', item.teamName)
      },
      querySearchInTeam(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        if (queryString) {
          const params = {
            teamName: queryString
          }
          selectTeam(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.teamName
            }
            let nameList = response.responseBody
            if (nameList.length === 0) {
              nameList = [{ value: '暂无数据' }]
            }
            callback(nameList)
          })
        } else {
          callback([])
        }
      },
      handleSelectInTeam(item) {
        this.teamRow.inTeamName = item.teamName
      },
      querySearchName(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        if (queryString) {
          const params = {
            name: queryString,
            teamId: this.teamRow.originalTeamId
          }
          selectOperator(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.name
            }
            let nameList = response.responseBody
            if (nameList.length === 0) {
              nameList = [{ value: '暂无数据' }]
            }
            callback(nameList)
          })
        } else {
          callback([])
        }
      },
      handleSelectName(item) {
        let obj = {}
        if (item.secondarySector) {
          obj = global.secondarySectorList.find((items) => {
            return items.value === item.secondarySector
          })
        }
        this.$set(this.teamRow, 'employeeId', item.employeeId)
        this.$set(this.teamRow, 'name', item.name)
        this.$set(this.teamRow, 'originalPosition', item.originalPosition)
        this.$set(this.teamRow, 'rank', item.rank)
        this.$set(this.teamRow, 'sex', item.sex)
        this.$set(this.teamRow, 'primarySector', item.primarySector)
        this.$set(this.teamRow, 'secondarySector', item.secondarySector)
        this.$set(this.teamRow, 'secondarySectorName', obj.label)
        this.$set(this.teamRow, 'tertiarySector', item.tertiarySector)
        this.$set(this.teamRow, 'teamId', item.teamId)
        this.$set(this.teamRow, 'teamName', item.teamName)
        console.log(this.teamRow)
      }
    },
    mounted() {
      console.log(this.pca)
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .app-container {
    .el-pagination {
      margin-top: 20px;
    }
    .table-btn {
      margin-bottom: 10px;
      & > button {
        margin: 0 20px;
      }
      .el-dialog {
        textarea {
          margin-top: 10px;
        }
        .el-checkbox {
          margin-right: 20px;
        }
        .el-checkbox + .el-checkbox {
          margin-left: 0;
        }
      }
    }
  }

</style>


<style rel="stylesheet/scss" lang="scss">
  .el-input__icon {
    line-height: 100%;
  }

  .el-form-item__content {
    line-height: 33px;
  }

  .area-select .area-selected-trigger {
    padding: 0 10px;
  }

  /*.el-table__body tr.hover-row>td {
    background-color: #0000ff !important;
  }

  .el-table__body tr.current-row>td {
    background-color: #0000ff !important;
  }*/
</style>
